package server;

import java.io.IOException;
import java.lang.reflect.Method;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class MyClassLoader extends ClassLoader {

    private String basePath;

    public String getBasePath() {
        return basePath;
    }

    public void setBasePath(String basePath) {
        this.basePath = basePath;
    }

    @Override
    protected Class<?> findClass(String name) {
        String myPath = basePath + name.replace(".","/") + ".class";
        byte[] cLassBytes = null;
        Path path = null;
        try {
            path = Paths.get(myPath);
            cLassBytes = Files.readAllBytes(path);
        } catch (IOException e) {
            e.printStackTrace();
        }
        Class clazz = defineClass(name, cLassBytes, 0, cLassBytes.length);
        return clazz;
    }

    public static void main(String[] args) throws ClassNotFoundException {
        MyClassLoader loader = new MyClassLoader();
        loader.setBasePath("D://webapps/app1/classes/");
        Class<?> aClass = loader.findClass("server.LagouServlet");
        try {
            Object obj = aClass.newInstance();
            Method method = aClass.getMethod("doGet",Request.class,Response.class);
            method.invoke(obj,new Request(),new Response());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
